package com.youlu.campus.admin.task;

import com.youlu.campus.service.activity.UserParticipateActivityInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class InvitedNumTask {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserParticipateActivityInfoService upService;

    private final String UPDATE_INVITE_NUM_KEY = "activity:invitedNum:update";

    /**
     * 每天00:05执行一次
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void doUpdateInvitedNum() {
        log.info("...>开始执行更新用户邀请人数量错误");
        Date date = new Date();
        try {
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(UPDATE_INVITE_NUM_KEY, "1", 3L, TimeUnit.HOURS);
            if (Objects.nonNull(flag) && !flag) {
                return;
            }
            upService.updateInvitedNum(date);
        } catch (Exception e) {
            log.error("...:>>> 更新活动邀请人数量错误:{}", e);
        } finally {
            redisTemplate.delete(UPDATE_INVITE_NUM_KEY);
            log.info("结束执行更新用户邀请人数量,耗时:{} 毫秒", (new Date().getTime() - date.getTime()) / 1000);
        }


    }
}
